# -*- coding: utf-8 -*-

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from lxml import etree
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time
from fake_useragent import UserAgent


# 初始化
def init_driver(url):
    chrome_options = Options()
    # fire_options.add_argument('--headless') # 无头模式
    # chrome_options.add_argument('--disable-gpu')
    chrome_options.add_experimental_option('excludeSwitches', ['enable-automation']) # 设置开发模式，避免被检测
    chrome_options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36')  # 修改请求头，伪装浏览器型号
    # driver = webdriver.Chrome(chrome_options=chrome_options) # 已经设置PATH环境变量
    # 未在PATH环境变量中设置，需要设置驱动可执行路径
    # chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
    driver = webdriver.Chrome(executable_path='D:\\webdriver\\chromedriver.exe', chrome_options=chrome_options)
    driver.maximize_window()  # 浏览器最大化
    driver.get(url)
    # html = driver.page_source
    # print(html)
    return driver


# 获取页面url
def get_url(drive):
    # 设置等待
    wait = WebDriverWait(driver, 20)

    # WebDriverWait(driver, 50).until(
    #     EC.presence_of_element_located((By.XPATH, '//a[contains(text(),"下一页")]')))

    driver.find_element_by_css_selector('[class="searchKey search-inp"]').send_keys("鞍山市政工程有限公司")
    driver.find_element_by_css_selector('[class="search-rightBtn search-click"]').click()
    while True:
        html = etree.HTML(driver.page_source)
        for t in html.xpath('//div[@class="LM_list"]'):
            type = t.xpath('./div/div[@class="labelTwo"]/text()')[0]
            urlChild = t.xpath('./div[@class="list_title clearfix"]/h4/a/@href')[0]
            title = t.xpath('./div[@class="list_title clearfix"]/h4/a/text()')[0]
            fy = t.xpath('./div[@class="list_subtitle"]//span/text()')[0]
            haoma = t.xpath('./div[@class="list_subtitle"]//span/text()')[1]
            riqi = t.xpath('./div[@class="list_subtitle"]//span/text()')[2]
            reason = "".join(t.xpath('./div[@class="list_reason"]//text()')).strip()
            # 获取当前窗口句柄
            now_handle = driver.current_window_handle
            js = f'window.open("{urlChild}");'
            driver.execute_script(js)
            time.sleep(2)
            # 获取所有窗口句柄
            all_handles = driver.window_handles
            for handle in all_handles:
                if handle != now_handle:
                    driver.switch_to.window(handle)
                    html = etree.HTML(driver.page_source)
                    bh = "".join(html.xpath('//div[@id="1"]/text()'))
                    bh = "".join(html.xpath('//div[@style="TEXT-ALIGN: right; LINE-HEIGHT: 25pt; MARGIN: 0.5pt 0cm;  FONT-FAMILY: 宋体;FONT-SIZE: 15pt; "]/text()'))
                    reason1 = ""
                    # （正文内容）、（法官助理、书记员）
                    list1 = html.xpath('//div[contains(@style,"LINE-HEIGHT: 25pt; TEXT-INDENT: 30pt; MARGIN: 0.5pt 0cm;FONT-FAMILY: 宋体; FONT-SIZE: 15pt;")]//text()')
                    # 审判长、审判员、日期
                    list2 = html.xpath('//div[@style="TEXT-ALIGN: right; LINE-HEIGHT: 25pt; MARGIN: 0.5pt 36pt 0.5pt 0cm;FONT-FAMILY: 宋体; FONT-SIZE: 15pt;"]//text()')
                    # 标题
                    list3 = html.xpath('//div[@style="TEXT-ALIGN: center; LINE-HEIGHT: 25pt; MARGIN: 0.5pt 0cm; FONT-FAMILY: 黑体; FONT-SIZE: 18pt;"]//text()')
                    # 法官助理、书记员
                    list4 =[]
                    i = 0
                    # 添加标题
                    for t in list3:
                        reason1 += t + "\r\n"
                    # 拼接正文内容、审判长、法官助理、书记员
                    for l in list1:
                        if len(list1) - 2 == i:
                            for l1 in list2:
                                reason1 += l1 + "\r\n"
                        reason1 += l + "\r\n"
                        if i >= len(list1) - 2:
                            list4.append(l)
                        i += 1
                    driver.close()
            # 返回主窗口
            driver.switch_to.window(now_handle)
            print("=================")
            print(type)
            print(urlChild)
            print(fy)
            print(haoma)
            print(riqi)
            print(reason)
        time.sleep(2)
        # js = "document.getElementsByClassName('pageButton')[5].click();"
        # driver.execute_script(js)
        # 点击下一页
        driver.find_element_by_xpath('//a[contains(text(),"下一页")]').click()
        # 点击下一页



def close_driver(driver):
    driver.quit()


if __name__ == '__main__':
    url = "http://wenshu.court.gov.cn/"
    driver = init_driver(url)
    for page in range(1):
        get_url(driver)
